package com.demo.mybaits.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.demo.mybaits.sqlsession.SqlSessionProvider;

public class SeverletFilter implements Filter {
	private final static Logger log = LoggerFactory.getLogger(SqlSessionProvider.class);

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		SqlSession sqlSession = SqlSessionProvider.INSTANCE
				.getSessionByUri(((HttpServletRequest) request).getRequestURI());
		
		try {
			System.out.println(((HttpServletRequest) request).getRequestURI());
			chain.doFilter(request, response);
			
			sqlSession.commit(); // 提交事务
			
			log.info("提交事务成功");
		} catch (Exception e) {
			try {
				log.error("提交事务发生异常，回滚",e);
				sqlSession.rollback();
			} catch (Exception e1) {
				log.error("数据库回滚发生异常", e1);
				throw e1;
			}
		} finally {
			SqlSessionProvider.INSTANCE.closeSqlSession();
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
